/*
 * circularlist.cpp
 *
 *  Created on: Feb 9, 2010
 *      Author: rohithdv
 */

#include "node.h"
#include "circularlist.h"
#include <iostream>
using namespace std;

circularlist::circularlist() {
	rollBackOccurred = false;
	playerIndex = -1;
	header = NULL;
	currPointer = NULL;
}

circularlist::~circularlist() {

	cout << "Circular List destructor called for player: " << playerIndex << endl;
	node * temp = header;
	node * nextElement = NULL;

	temp = header->getNextNode();

	while (temp != header) {
		nextElement = temp->getNextNode();
		delete temp;
		temp = nextElement;
	}
	delete temp;
	header = temp = NULL;
	currPointer = NULL;;
	lastNode = NULL;
}

void circularlist::display() {
	node * temp = header;

	// reset currpointer
	reset();

	cout << "Circular List Contents for player " << playerIndex << ": " ;
	while (temp != currPointer) {
		temp->display();
		temp = temp->getNextNode();
	}
	temp->display();
	cout << endl;
}

void circularlist::updateList(int playerind, int noofstrategies) {
	node *newNode = NULL;
	rollBackOccurred = false;
	playerIndex = playerind;

	for (int i=1; i<= noofstrategies; i++) {
		if (header == NULL) {
			newNode = new node(i);
			header = newNode;
		}
		else {
			node *tempPtr = header;
			while (tempPtr->getNextNode() != NULL){
				tempPtr = tempPtr->getNextNode();
			}
			newNode = new node(i);
			tempPtr->setNextPointer(newNode);
		}
	}

	lastNode = newNode->setNextPointer(header);
	currPointer = lastNode;
}

bool circularlist::incrementPointer() {
	currPointer = currPointer->getNextNode();
	if (currPointer == header) {
		rollBackOccurred = true;
	}
	else {
		rollBackOccurred = false;
	}
	return rollBackOccurred;
}

int circularlist::returnCurrPointerValue() {
	return currPointer->getValue();
}

void circularlist::reset() {
	currPointer = lastNode;
}

void circularlist::deleteEntry(int strategyNumber) {
	node *temp = header;
	node *prev = header;

	while (temp->getValue() != strategyNumber) {
		prev = temp;
		temp = temp->getNextNode();
		if (temp == header) {
			// already examined the header. means that the data is not present in the list
			break;
		}
	}

	if (temp->getValue() == strategyNumber) {
		if (temp == header) {
			node *newheader = temp->getNextNode();

			if (newheader == header) {
				delete temp;
				header = NULL;
				lastNode = NULL;
			}
			else {
				node *temp1 = temp;
				// traverse till last Node and reset pointer to header
				while (temp1->getNextNode() != header)
					temp1 = temp1->getNextNode();
				temp1->setNextPointer(newheader);
				delete temp;
				temp = NULL;
				header = newheader;
			}
		}
		else {
			if (temp == lastNode) {
				lastNode = prev;
			}
			prev->setNextPointer(temp->getNextNode());
			delete temp;
			temp = NULL;
		}
	}
	else {
		cout << "circularlist::deleteEntry::: Strategy " << strategyNumber << " NOT FOUND !! in player " << playerIndex << "'s circular list" << endl ;
	}
}
